import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import { fetchGetAllTvwallStyles, fetchGetStyleById } from '@/api/create/tvwall'
import {
	BoxInfoEntity,
	boxPositionsEntity,
	CashSourceEntity,
	MeetingOrTemplateInterfaceTwallInfo,
	StyleInfoDetail,
	StyleInfoEntity,
	TvWallMemberItemEntity,
} from './interface'
import { useUserAllStore } from '../user/all/store'
import { UserEntity } from '@/api/create/interface'
import { Vmp } from '../vmp/interface'
import { t } from 'i18next'
import { PlanEntity, RevertPlanEntity } from './TvwallPlan/interface'
import { getTvWallTypeName, initOneTvwall, setInitCashData } from './store.combine'
import Alert from '@/components/Alert'
import { useMeetingParamsStore } from '../meetingParams/store'

type StateStore = {
	enable: boolean
	tDefault: number
	mode: number //1：定制画面，2：批量轮询
	/**选中的预案*/
	planValue: string
	/**是否配置了电视墙 */
	is_empty: boolean
	/**返回的所有可选的电视墙风格*/
	style_map: { [key: string]: BoxInfoEntity }
	/**当前使用的电视墙的风格通道的位置信息*/
	used_style_map: Array<BoxInfoEntity>
	/**配置(计算缩放的)*/
	config: {
		maxCell: number
		minWidth: number
		container: string
		containerW: number
		containerH: number
		MCCcontainerW: number
		previewW: number
		currentviewW: number
	}
	/**选中的电视墙风格*/
	correct_style: string
	/**新增模态框的开启*/
	isAddStyleModalOpen: boolean
	/**操作当前的通道*/
	operateItem: StyleInfoEntity | null
	/**批量轮询成员*/
	batch_poll_members: UserEntity[]
	show_mt_name: number

	// TvwallPlan  电视墙预案组件的值
	/**电视墙预案的名称*/
	tvwallPlanName: string
	/**电视墙预案对应的id */
	tvwallPlanValue: string
	/**电视墙预案*/
	planOptions: Array<RevertPlanEntity>
	needUpdate: any
	/**电视墙member具体信息(不包含位置信息)*/
	boxDetailVOsSource: Array<TvWallMemberItemEntity>
	/**VmpPoll用到的元素*/
	/**轮询预案 */
	pollPlanOptions: Array<RevertPlanEntity>
	pollPlanValue: string
	pollIntervalOptionsVal: number
	pollInterval: string
	pollTimes: string
	unlimited: boolean
	pollPlanName: string
	pollMembers: Array<UserEntity>
	isVmpOpen: boolean
	/**四分屏开启 */
	isFourScreenOpen: boolean
	/**单通道轮序的开启 */
	isSinglePollOpen: boolean
	/**当前通道状态(在离线是否被占用 位置信息等等)*/
	correct_style_positions: Array<boxPositionsEntity>
	/**用来存储缓存数据*/
	operate_correct_style_info: { [key: string]: Partial<CashSourceEntity> }
	/**当前对应选中风格操作的通道(存储hdu_id) 单通道轮询设置*/
	correct_style_operate_box_info: string
	isNeedUpdate: boolean
} & MeetingOrTemplateInterfaceTwallInfo

type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	/**电视墙入口（包含判断配置了电视墙/初始化会议接口数据）*/
	init: (d: MeetingOrTemplateInterfaceTwallInfo | null) => void
	/**
	 * 获取该平台是否配置了电视墙
	 * 存在 根据会议详情信息当中的style_id匹配对应的位置信息
	 * 未存在提示尚未配置电视墙
	 * 回调主要就是初始化接口数据 initData
	 * */
	isHasStyle: (callback?: () => void) => void
	/**初始化会议详情信息*/
	initData: (_d: MeetingOrTemplateInterfaceTwallInfo | null) => void
	/**
	 * 导入预案  nowStyleId需要展示的电视墙ID
	   转换电视墙数据
	   */
	importTVwallData: (_d: MeetingOrTemplateInterfaceTwallInfo | null, id?: string, isDellNotExisMt?: boolean) => void
	/**主要是设置used_style_map*/
	getUsedStyleMap: (_d: MeetingOrTemplateInterfaceTwallInfo['tvwalls']) => Array<BoxInfoEntity>
	/**添加终端进入批量轮询 */
	addAllMtToBatchPoll: (superMtNum: boolean) => void
	/**获取风格id对应的界面信息*/
	getTvwallInfoCacheById: (id: string) => StyleInfoEntity | null
	loadTvwallStyle: (id: string, callback: (d: StyleInfoDetail) => void) => void
	/**设置每个占用风格的通道设置信息缓存 */
	setAllTvwallInfoCacheById: (_d: MeetingOrTemplateInterfaceTwallInfo['tvwalls']) => void
	/**缓存数据(暂无意义) */
	setTvwallInfoCacheById: (id: string, info: StyleInfoEntity) => void
	/**初始化电视墙(根据创会返回的数据初始化)*/
	initTvwallStyle: (d: StyleInfoDetail) => void
	/**渲染新增风格缩略图 */
	// renderNewSelectedView: (d: any) => void
	/**批量轮询初始化*/
	// tvwallPollInit: (d: StyleInfoEntity['batch_poll'] | null) => void
	/**设置批量轮询的数据*/
	setBatchPollParams: (d: Partial<Vmp['poll']>) => void
	/**获取码率 */
	getRate: (_type: string) => number
	/**解析数据*/
	convertMsg: (d: any) => void
	/**记录当前的分格操作 (主要设置operate_correct_style_info)*/
	setOperteUsedStyleMap: (styleId: string, _d: Partial<CashSourceEntity>) => void
	setOperteUsedStyleMapPoll: (style: string, _d: Partial<CashSourceEntity>) => void
	setOperteUsedStyleMapHduId: (style: string, _d: Partial<TvWallMemberItemEntity>) => void
	checkTvwallPollData: () => boolean
}

const initialState: StateStore = {
	tvwallPlanValue: '0',
	tvwallPlanName: '',
	isNeedUpdate: false,
	/**风格对应的位置信息*/
	isVmpOpen: false,
	correct_style_positions: [],
	enable: false,
	/**默认智能混音 */
	mode: 1,
	/**预案名称 */
	name: '',
	id: '',
	tDefault: 0,
	planValue: '',
	planOptions: [{ label: t('不使用预案'), value: '0' }],
	tvwalls: [],
	style_map: {},
	used_style_map: [],
	is_empty: false,
	config: {
		maxCell: 10, //纵向或横向单元格最大数
		minWidth: 190,
		container: '',
		containerW: 900,
		containerH: 588,
		MCCcontainerW: 580,
		previewW: 135,
		currentviewW: 64,
	},
	correct_style: '',
	isAddStyleModalOpen: false,
	operateItem: null,
	batch_poll_members: [],
	show_mt_name: 1,
	pollPlanOptions: [{ label: t('不使用预案'), value: '0' }],
	pollPlanValue: '0',
	pollIntervalOptionsVal: 30,
	pollInterval: '5',
	pollTimes: '',
	unlimited: true,
	pollPlanName: '',
	pollMembers: [],
	needUpdate: {},
	isFourScreenOpen: false,
	isSinglePollOpen: false,
	boxDetailVOsSource: [],
	operate_correct_style_info: {},
	correct_style_operate_box_info: '',
}

export const useMeetingTVWallStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		setOperteUsedStyleMap: (id, data) => {
			const { operate_correct_style_info } = get()
			let source = {}
			if (data) {
				source = Object.assign({}, operate_correct_style_info[id], { ...data })
			}
			operate_correct_style_info[id] = source
			console.log('operate_correct_style_info****************', operate_correct_style_info)
			set({ operate_correct_style_info: operate_correct_style_info })
		},
		setOperteUsedStyleMapPoll: (id, data) => {
			const { operate_correct_style_info } = get()
			let source = {}
			if (data) {
				source = Object.assign({}, operate_correct_style_info[id], { ...data })
			}
			operate_correct_style_info[id] = source
			console.log('operate_correct_style_info****************', operate_correct_style_info)
			set({ operate_correct_style_info: operate_correct_style_info })
		},
		setOperteUsedStyleMapHduId: (id, data) => {
			const { operate_correct_style_info } = get()
			let source = {}
			if (data) {
				/**找到当前通道对应的盒子*/
				let member = operate_correct_style_info[id]?.members || []
				let flag = member?.some((item) => {
					return item.hdu_id === data.hdu_id
				})
				if (flag) {
					/**能找到替换 */
					for (let i = 0; i < member.length; i++) {
						if (member[i].hdu_id === data.hdu_id) {
							member[i] = data
						}
					}
				} else {
					/**不能找到新增*/
					member?.push(data)
				}

				source = Object.assign({}, operate_correct_style_info[id], { members: member })
			}
			operate_correct_style_info[id] = source
			console.log(
				'operate_correct_style_info****************setOperteUsedStyleMapHduId调用',
				operate_correct_style_info
			)
			set({ operate_correct_style_info: operate_correct_style_info })
		},

		initTvwallStyle: (data) => {
			// if (!data) return
			// if (!self.isInit) this.init() //初始化入口   如果未初始化 则进行初始化
			// var dom = self.$tvwallContent.empty()
			// set({ correct_style: data.style_id })
			// drawMCCWall(dom, data.boxDetailVOs, 'mcc')
			// self.initBoxMenu() //界面显示  每个通道 的 设置 取消  删除等操作
			// self.setHDU() //设置hdu信息
			// self.initBoxEvect() //每个格子的中的事件   Evnent
		},
		setBatchPollParams: (d) => {
			set({ pollMembers: d?.members })
		},
		// changeTvwallStyleDTO: function (styleDTO) {
		// 	const { batch_poll, members, mode, show_mt_name, style_id } = styleDTO
		// 	return {
		// 		memberList: mode === 1 ? TS.paramsTrans.changeTvwallMemberDTOArr(members) : null,
		// 		showMTName: show_mt_name,
		// 		style: style_id,
		// 		tvWallBatchPoll: mode === 2 ? TS.paramsTrans.changePollDTO(batch_poll) : null,
		// 	}
		// },
		/**
		 * @param _source  会议或者模板详情电视墙信息
		 */
		init: (_source) => {
			const { isHasStyle, initData } = get()
			let callBack = () => {
				initData(_source)
			}
			isHasStyle(callBack)
		},
		isHasStyle: async (callback) => {
			const res = await fetchGetAllTvwallStyles()
			if (res.success) {
				if (res.data && res.data.length > 0) {
					let _result: { [key: string]: BoxInfoEntity } = {}
					for (var i = 0; i < res.data.length; i++) {
						const current = res.data[i]
						_result[current.id] = current
					}
					set({ style_map: _result, is_empty: false })
					callback && callback()
					return
				} else {
					set({ is_empty: true })
					return
				}
			}
		},
		initData: (_data) => {
			const { importTVwallData } = get()
			/**数据处理 */
			if (_data && JSON.stringify(_data) !== '{}') {
				const { id = '', name, tvwalls } = _data
				set({ enable: true, name: name, id: id, tDefault: 0, tvwalls: tvwalls })
			} else {
				set({
					enable: false,
					id: '',
					name: '',
					tDefault: 0,
					tvwalls: [],
				})
			}
			importTVwallData(_data ?? null)
		},
		checkTvwallPollData: () => {
			const { mode, unlimited, pollInterval, pollTimes, pollIntervalOptionsVal, pollMembers } = get()
			if (mode === 4) {
				if (pollIntervalOptionsVal === 0) {
					if (pollInterval === '') {
						Alert(t('请设置轮询间隔'))
						return false
					} else if (Number(pollInterval) < 5 || Number(pollInterval) > 7200) {
						Alert(t('轮询间隔应为5~7200秒'))
						return false
					}
				}
				if (!unlimited) {
					if (pollTimes === '') {
						Alert(t('请设置轮询次数'))
						return false
					} else if (Number(pollTimes) < 1 || Number(pollTimes) > 9999) {
						Alert(t('轮询次数应为1~9999次'))
						return false
					}
				}
				if (pollMembers.length === 0) {
					Alert(t('批量轮询列表不能为空'))
					return false
				}
				return true
			}
			return true
		},
		importTVwallData: (_data, style_id, isDellNotExisMt) => {
			setInitCashData(_data)
			const { tvwalls = [] } = _data || {}
			const { getUsedStyleMap, setAllTvwallInfoCacheById, getTvwallInfoCacheById } = get()
			const _used_style_map = getUsedStyleMap(tvwalls)
			set({ used_style_map: _used_style_map }) /**设置使用的风格 */
			//渲染本会议所有电视墙风格列表
			// renderAllSelectedView(myUsedStyle)
			if (tvwalls && tvwalls.length > 0) {
				// if (isDellNotExisMt) {
				// 	dellNotExisMt(tvwalls)
				// }
				setAllTvwallInfoCacheById(tvwalls)
				if (style_id) {
					/**如果存在风格就要指定渲染风格（获取详情渲染）*/
					let currentDate = getTvwallInfoCacheById(style_id)
					initOneTvwall(currentDate)
				} else {
					/**否则话将第一个当做渲染的风格*/
					let currentDate = tvwalls[0] //默认显示第一个风格数据
					initOneTvwall(currentDate)
				}
			}
		},
		setAllTvwallInfoCacheById: (tvwalls) => {
			const { setTvwallInfoCacheById } = get()
			for (var i = 0; i < tvwalls.length; i++) {
				var tvwallInfo = tvwalls[i]
				var styleId = tvwallInfo.style_id
				setTvwallInfoCacheById(styleId, tvwallInfo)
			}
		},
		setTvwallInfoCacheById: function (styleId, tvwallInfo) {
			//缓存数据
			// var that = this
			// var $oldStyle = that.$tviewWrap.find('li#' + styleId) //获取点击当前选中的风格Dom
			// $oldStyle.data('tvwallInfo', tvwallInfo) //缓存数据
		},
		getUsedStyleMap: (tvwalls) => {
			const { style_map } = get()
			let result = tvwalls.map((item) => {
				const key = item.style_id
				const _v = style_map[key]
				return _v
			})
			return result
		},
		getTvwallInfoCacheById: (styleId: string) => {
			const { tvwalls } = get()
			return (
				tvwalls.find((item) => {
					const key = item.style_id
					return key === styleId
				}) ?? null
			)
		},
		addAllMtToBatchPoll: (superMtNum) => {
			const tree = useUserAllStore.getState().tree
			let memberList = tree
				.filter((x) => x.mcc.account_type !== 10 && (superMtNum ? x.mcc.interactive_mt === 1 : true))
				.map((item) => {
					return item.mcc
				})
			set({ batch_poll_members: memberList })
		},
		loadTvwallStyle: async (id, callback) => {
			if (id) {
				const res = await fetchGetStyleById(id)
				if (res.success) {
					if (typeof callback == 'function') {
						callback(res)
					}
				}
			}
		},
		convertMsg: (source) => {
			if (!source) {
				return {
					type: 0,
				}
			}
			const { member_type, account, account_type } = source
			if (member_type === 1 && (!account || !account_type)) {
				/**1-会控指定(并且没有终端) */
				return {
					type: 0,
				}
			}
			if (member_type === 1 && account && account_type) {
				return {
					type: member_type,
					_mtName: source.name,
					...source,
				}
			}
			if (
				member_type === 2 ||
				member_type === 3 ||
				member_type === 4 ||
				member_type === 6 ||
				member_type === 10 ||
				member_type === 11
			) {
				let _mtName = source.name || ''
				return {
					type: member_type,
					name: getTvWallTypeName(member_type),
					_mtName: _mtName.replace(/\s/g, '&nbsp;'),
				}
			}
			if (member_type === 8) {
				/**自主多画面*/
				return {
					type: 8,
					mt_id: '',
					name: t('自主多画面'),
				}
			}
			if (member_type === 5 /**单通道*/) {
				return {
					type: 5,
					name: t('单通道轮询'),
					mtName: '',
				}
			}
			if (member_type === 9 /**四分屏*/) {
				return {
					type: 9,
					name: t('四分屏'),
					mtName: '',
				}
			}
		},
		/**获取码率 */
		getRate: (type) => {
			let rate: number = 1
			const { config } = get()
			switch (type) {
				case 'preview':
					rate = config.previewW / config.containerW
					break
				case 'currentview':
					rate = config.currentviewW / config.containerW
					break
				case 'mcc':
					rate = config.MCCcontainerW / config.containerW
					break
			}
			return rate
		},
		// refreshTvwallList: (templateTVWallVO) => {
		// 	var self = this
		// 	if (!templateTVWallVO) {
		// 		templateTVWallVO = self.getPara()
		// 	}
		// 	var nowStyleId = self.getCurStyleIdCache()
		// 	self.importTVwallData(templateTVWallVO, nowStyleId, true)
		// },
	}))
)
